package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 18.妖盟管理
 */
@RestController
@RequestMapping("/game/admin")
public class AdminUnionController {

    /**
     * 18.2 查询
     */
    @ResponseBody
    @RequestMapping(value = "union/search", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchUnion(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        long serverId = jsonObject.getLongValue("serverId");

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");
        String unionUid = jsonObject.getString("monsterLeagueId");
        String unionName = jsonObject.getString("monsterLeagueName");
        String orderSortHT = jsonObject.getString("orderSortHT");
        String orderByColumnHT = jsonObject.getString("orderByColumnHT");

        List<CrossUnionInfo> resultUnionInfos = new ArrayList<>();

        if(!StringUtils.isNullOrEmpty(unionUid)){
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfoMap().get(unionUid);
            if(unionInfo == null){
                unionInfo = CrossUnionMgr.getDeleteUnionInfoMap().get(unionUid);
                if(unionInfo != null){
                    resultUnionInfos.add(unionInfo);
                }
            }
        }else if(!StringUtils.isNullOrEmpty(unionName)){
            List<CrossUnionInfo> allList = new ArrayList<>();
            allList.addAll(CrossUnionMgr.getUnionInfoMap().values());
            allList.addAll(CrossUnionMgr.getDeleteUnionInfoMap().values());
            for (CrossUnionInfo unionInfo : allList) {
                if (!unionInfo.getUnionName().contains(unionName)) {
                    continue;
                }
                resultUnionInfos.add(unionInfo);
            }
        }else {
            List<CrossUnionInfo> allList = new ArrayList<>();
            allList.addAll(CrossUnionMgr.getUnionInfoMap().values());
            allList.addAll(CrossUnionMgr.getDeleteUnionInfoMap().values());
            resultUnionInfos = allList;
        }


        if("asc".equals(orderSortHT)){
            resultUnionInfos.sort(Comparator.comparing(UnionInfo::getTotalEarnSpeed));
        }else {
            resultUnionInfos.sort((o1, o2) -> o2.getTotalEarnSpeed().compareTo(o1.getTotalEarnSpeed()));
        }

        List<CrossUnionInfo> pageUnionInfos = new ArrayList<>();
        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        for (int i = startIndex; i < startIndex + pageSize && i < resultUnionInfos.size(); i++) {
            pageUnionInfos.add(resultUnionInfos.get(i));
        }

        List<Map<String, Object>> list = new ArrayList<>();
        AdminResult adminResult = AdminResult.defaultInstance();
        adminResult.getData().put("total", pageUnionInfos.size());
        for (CrossUnionInfo unionInfo : pageUnionInfos) {
            Map<String, Object> map = new HashMap<>();
            map.put("channelId", channelId);
            map.put("serverId", unionInfo.getServerId());
            map.put("monsterLeagueId", unionInfo.getUnionUid());
            if(StringUtils.isNullOrEmpty(unionInfo.getUnionFlagStr())){
                map.put("monsterLeagueFlag", unionInfo.getUnionFlag());
            }else {
                map.put("monsterLeagueFlag", unionInfo.getUnionFlagStr());
            }
            map.put("monsterLeagueName", unionInfo.getUnionName());
            map.put("leagueMasterId", unionInfo.getMasterUserId());
            map.put("randomlyJoin", unionInfo.isAllowRandomJoin());
            map.put("monsterLeagueAllPower", unionInfo.getTotalEarnSpeed().toString());
            map.put("joinLimit", CrossUnionMgr.getUnionMaxMemberSize(unionInfo.getUnionUid()));
            map.put("notice", unionInfo.getOutNotice());
            map.put("declaration", unionInfo.getInnerNotice());
            map.put("recruitInfo", Collections.emptyList());
            map.put("leaderWechat", unionInfo.getWechatCode());
            map.put("level", UnionConfigMgr.getUnionLv(unionInfo.getExperience()));
            map.put("status", unionInfo.isDelete() ? 0 : 1);
            list.add(map);
        }

        adminResult.getData().put("row", list);

        return adminResult.toJsonString();
    }


    /**
     * 18.3 妖盟成员列表
     */
    @ResponseBody
    @RequestMapping(value = "union/memberList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String memberList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        AdminResult2 adminResult = AdminResult2.defaultInstance();

        String unionUid = jsonObject.getString("monsterLeagueId");

        if(StringUtils.isNullOrEmpty(unionUid)){
            adminResult.setMsg("参数缺失");
            return adminResult.toJsonString();
        }

        CrossUnionInfo crossUnionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if(crossUnionInfo == null || memberMap == null){

        }else {
            String orderSortHT = jsonObject.getString("orderSortHT");
            List<CrossUnionMember> list = new ArrayList<>(memberMap.values());
            if("asc".equals(orderSortHT)){
                list.sort(Comparator.comparing(o -> o.getUserBaseInfo().getEarnSpeed()));
            }else {
                list.sort((o1, o2) -> o2.getUserBaseInfo().getEarnSpeed().compareTo(o1.getUserBaseInfo().getEarnSpeed()));
            }
            for (CrossUnionMember member : list) {
                Map<String,Object> object = new HashMap<>();
                object.put("userId", member.getUserId());
                object.put("userName", member.getUserBaseInfo().getNickName());
                object.put("level", member.getUserBaseInfo().getTitleId());
                object.put("power", member.getUserBaseInfo().getEarnSpeed().toString());
                object.put("jobTitle", eUnionPosition.getPositionName(member.getPosition()));
                UserInfo userInfoInRAM = UserMgr.getUserInfoInRAM(member.getUserId());
                if(userInfoInRAM != null) {
                    object.put("openId", userInfoInRAM.getOpenId());
                }
//                object.put("todayCont", member.getTodayContribution());
//                object.put("quitTime", member.getQuitTime());
//                object.put("kickTime", member.getKickTime());
//                object.put("joinTime", member.getJoinTime());
//                object.put("dayKickNum", member.getDayKickNum());
//                object.put("historyMaxAbility", member.getHistoryMaxAbility().toString());
                adminResult.getData().add(object);
            }
        }
        return adminResult.toJsonString();
    }

    /**
     * 18.4 盟主转移
     */
    @ResponseBody
    @RequestMapping(value = "union/transferUnion", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String transferUnion(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        String unionUid = jsonObject.getString("monsterLeagueId");
//        long masterUserId = jsonObject.getLongValue("masterUserId");
        long userId = jsonObject.getLongValue("userId");

        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            return AdminResult.defaultInstance().setMsg("找不到商会").toJsonString();
        }else {
//            if(masterUserId != unionInfo.getMasterUserId()){
//                return AdminResult.defaultInstance().setMsg("当前会长错误").toJsonString();
//            }
        }

        GamePlayer player = GamePlayerMgr.getPlayer(unionInfo.getMasterUserId());
        if (player == null) {
            return AdminResult.defaultInstance().setMsg("找不到转让的玩家").toJsonString();
        }

        CrossUnionProto.UnionPositionSetCrossReqMsg.Builder crossReq = CrossUnionProto.UnionPositionSetCrossReqMsg.newBuilder().setPosition(eUnionPosition.Master.getValue()).setUserId(userId);
        crossReq.setIsBack(true);
        player.sendPacket(Protocol.C_UNION_POSITION_SET, crossReq);

        return AdminResult.defaultInstance().toJsonString();
    }
}
